package com.ruoyi.charge.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.solon.service.impl.ServiceImpl;
import com.ruoyi.charge.domain.ChargerGun;
import com.ruoyi.charge.mapper.ChargerGunMapper;
import com.ruoyi.charge.service.IChargerGunService;
import com.ruoyi.common.constants.CacheConstant;
import com.ruoyi.common.utils.RedisUtil;
import com.ruoyi.common.web.exception.ServiceException;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;

import java.util.List;

/**
 * 充电枪 服务层实现
 *
 * @author laifeng
 */
@Component
public class ChargerGunServiceImpl extends ServiceImpl<ChargerGunMapper, ChargerGun> implements IChargerGunService {

    @Inject
    ChargerGunMapper chargerGunMapper;
    @Inject
    RedisUtil redisUtil;

    @Override
    public List<ChargerGun> getChargerGunListCacheBySn(String sn) {
        List<ChargerGun> chargerGunList = redisUtil.getCacheList(CacheConstant.getChargerGunListBySn(sn));
        if (CollUtil.isEmpty(chargerGunList)) {
            chargerGunList = this.list(new QueryWrapper().eq(ChargerGun::getChargerSn, sn));
            if (ArrayUtil.isNotEmpty(chargerGunList)) {
                redisUtil.setCacheList(CacheConstant.getChargerGunListBySn(sn), chargerGunList);
            }
        }
        return chargerGunList;
    }

    @Override
    public ChargerGun getChargerGunCacheBySnAndNumber(String sn, String number) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(ChargerGun::getChargerSn, sn)
                .eq(ChargerGun::getNumber, number);
        return chargerGunMapper.selectOneByQuery(queryWrapper);
    }

    @Override
    public boolean addChargerGun(ChargerGun chargerGun) {
        if (StrUtil.isEmpty(chargerGun.getChargerSn())) {
            throw new ServiceException("充电桩sn不能为空");
        }
        delCacheToChargerGunList(chargerGun.getChargerSn());
        return this.save(chargerGun);
    }

    @Override
    public boolean updateByIdChargerGun(ChargerGun chargerGun) {
        if (StrUtil.isEmpty(chargerGun.getChargerSn())) {
            throw new ServiceException("充电桩sn不能为空");
        }
        delCacheToChargerGunList(chargerGun.getChargerSn());
        return this.updateById(chargerGun);
    }

    @Override
    public boolean removeChargerGunsByIds(List<Long> list) {
        List<ChargerGun> chargerGunList = this.listByIds(list);
        if (ArrayUtil.isNotEmpty(chargerGunList)) {
            for (ChargerGun chargerGun : chargerGunList) {
                delCacheToChargerGunList(chargerGun.getChargerSn());
            }
        }
        return this.removeByIds(list);
    }

    private void delCacheToChargerGunList(String sn) {
        redisUtil.deleteCacheList(CacheConstant.getChargerGunListBySn(sn));
    }
}
